package com.itcast.activiti.aop;


import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.security.Principal;
import java.util.Enumeration;

@Aspect
@Component
@Order(2)
@Slf4j
public class LogAspect {
    private static final String LINE_SEPARATOR = "，";
    private static final ThreadLocal<Long> startTime = new ThreadLocal<>();
    private static final ThreadLocal<StringBuilder> sb = new ThreadLocal<>();

    @Pointcut("execution(public * com.itcast.*.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        StringBuilder builder = new StringBuilder();
        startTime.set(System.currentTimeMillis());
        sb.set(builder);
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        builder.append("OAP Log intercept").append(LINE_SEPARATOR);
        builder.append("url : " + request.getRequestURL().toString()).append(LINE_SEPARATOR);
        builder.append("request : " + request.getMethod()).append(LINE_SEPARATOR);
        builder.append("class method : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()).append(LINE_SEPARATOR);

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] objects = joinPoint.getArgs();
        Parameter[] parameters = method.getParameters();

        for (int i = 0; i < parameters.length; i++) {
            Parameter p = parameters[i];
            if (p.getType().equals(HttpServletRequest.class)) {
                continue;
            }
            if (p.getType().equals(HttpServletResponse.class)) {
                continue;
            }
            if (p.getType().equals(Principal.class)) {
                continue;
            }
            if ("bytes".equalsIgnoreCase(p.getName())) {
                continue;
            }
            if (objects[i] != null) {
                try {
                    builder.append("args : " + JSON.toJSONString(ImmutableMap.of(p.getName(), objects[i]))).append(LINE_SEPARATOR);
                } catch (Exception e) {
                    log.error("json output args {} error {} ", p.getName(), e);
                }
            }
        }
    }

    @AfterReturning(pointcut = "log()", returning = "ret")
    public void doAfterReturning(Object ret) {
        // 处理完请求，返回内容
        StringBuilder builder = sb.get();
        builder.append("response : " + JSON.toJSONString(ret)).append(LINE_SEPARATOR);
        builder.append("time : " + (System.currentTimeMillis() - startTime.get()) + "ms").append(LINE_SEPARATOR);
        log.info(builder.toString());
    }

    @AfterThrowing(pointcut = "log()", throwing = "exp")
    public void doAfterThrowing(Exception exp) {
        // 处理完请求，返回内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        StringBuilder builder = new StringBuilder();
        // 记录下请求内容
        builder.append("OAP Log Exception intercept").append(LINE_SEPARATOR);
        builder.append("url : " + request.getRequestURL().toString()).append(LINE_SEPARATOR);
        builder.append("request : " + request.getMethod()).append(LINE_SEPARATOR);

        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            builder.append("args : " + JSON.toJSONString(ImmutableMap.of(paramName, paramValues))).append(LINE_SEPARATOR);
        }
        builder.append("exception : " + ExceptionUtils.getStackTrace(exp)).append(LINE_SEPARATOR);
        builder.append("time : " + (System.currentTimeMillis() - startTime.get()) + "ms");
        log.error(builder.toString());
    }
}
